package com.itheima;

import org.junit.Test;

import java.util.*;

public class Topic239 {


    public int[] maxSlidingWindow(int[] nums, int k) {

        int[] result = new int[nums.length - k + 1];
        List<Integer> list = new ArrayList<>();//滑动窗口
        Queue<Integer> q = new LinkedList<>();

        for(int i = 0; i < k; i++){
            q.add(nums[i]);
        }

        result[0] = q.stream().max(Integer::compare).get();
        for(int i = 1; i < nums.length - k + 1; i++){
            q.poll();
            q.add(nums[i + k - 1]);
            result[i] = q.stream().max(Integer::compare).get();
        }

        System.out.println(Arrays.toString(result));
        return result;
    }
    public int[] maxSlidingWindow2(int[] nums, int k) {

        int[] result = new int[nums.length - k + 1];
        Queue<int[]> q = new PriorityQueue<>(new Comparator<int[]>() {
            public int compare(int[] o1, int[] o2) {
                return o1[0] != o2[0] ? o2[0] - o1[0] : o2[1] - o1[1];
            }
        });

        for(int i = 0; i < k; i++){
            q.offer(new int[]{nums[i], i});
        }
        result[0] = q.peek()[0];
        for(int i = k; i < nums.length; ++i){
            q.offer(new int[]{nums[i], i});
            if(q.peek()[1] <= i - k){
                q.poll();
            }
            result[i - k + 1] = q.peek()[0];

        }
        System.out.println(Arrays.toString(result));
        return result;
    }


    @Test
    public void test() {
        maxSlidingWindow2(new int[]{9,10,9,-7,-4,-8,2,-6}, 5);
    }
}
